<template>
    <scroll-view id="tl-tabs-scroll-view"
                 scroll-x class="bg-white nav tl-tabs-components" :class="'azm-1px-' + border"
                 :scroll-with-animation="animation" :scroll-into-view="active_id">
        <view class="flex text-center">
            <view :id="`tl-tab-${index}`"
                  :class="{'flex-sub':labels.length > 1 && !position,
                  'justify-center':position==='center',
                  'justify-end':position==='right'}"
                  v-for="(item,index) in labels" :key="index" @tap="handleTabSelect" :data-id="index">
                <view class="cu-item no-border" :class="{'cu-item__active':index === active}"
                      :style="itemStyle">
                    <view class="cu-item__box">
                        <view class="cu-item__box__line" :style="lineStyle_"
                              v-if="!isClick && hideBorder !== true"/>
                        <text>{{item}}</text>
                    </view>
                </view>
            </view>
            <view v-show="isClick && hideBorder !== true" class="tl-tabs__line" :style="lineStyle"/>
        </view>
    </scroll-view>
</template>

<script>

    import { debounce } from "@u/lodash/throttle"

    import { mapState } from 'vuex'

    let timer;
    const $$$setTimeout = function (func, d) {
        clearTimeout(timer);
        timer = setTimeout(func, d)
    };

    export default {
        name: "tl-tabs",
        components: {},
        props: {
            tabs: {
                type: Array,
                default (n) {
                    return n || []
                }
            },
            value: {
                type: [String, Number],
                default: 0
            },
            val: {
                type: String,
                default: 'id'
            },
            position: {
                type: String,
                default: ''
            },
            label: {
                type: String,
                default: "label"
            },
            scale: {
                type: Number,
                default: 0.8
            },
            border: String,
            animation: Boolean,
            hideBorder: Boolean,
            itemStyle: String
        },
        data () {
            return {
                isClick: false,
                active: 0,
                active_id: '',
                lineStyle: '',
                lineStyle_: '',
                labels: [],
                type: 0
            }
        },
        computed: {
            ...mapState({
                systemInfo: state => state.User.systemInfo
            })
        },
        watch: {
            tabs (n) {
                this.init()
            },
            scale (n) {
                this.setLineStyle()
            },
            value (n, o) {
                this.setActive(n, o)
            }
        },
        mounted () {
            this.init()
        },
        methods: {
            setActive (n, o) {
                let that = this;
                const value = n || this.value;
                let id = 'tl-tab-0', fid, fIndex = 0;
                that.labels = that.tabs.map(val => {
                    if (typeof val === 'string') {
                        return val
                    } else if (that.label) {
                        return val[that.label]
                    }
                });
                fIndex = that.tabs.findIndex((val, index) => {
                    if (typeof val === 'string' && index === value) {
                        return true;
                    } else {
                        fid = val[that.val];
                        return val[that.val] === value;
                    }
                });
                if (fIndex > -1) {
                    id = `tl-tab-${fIndex}`;
                    that.active = fIndex;
                } else {
                    fIndex = 0;
                }
                if (that.isClick === false) {
                    $$$setTimeout(function () {
                        that.setLineAnimation2(id);
                    }, 500);
                }
                // console.log(that.tabs, value, fIndex, fid, '+++++++++++++++++++++++++++++++setActive++++++++++++++++++++++');
                return fid || fIndex;
            },
            setLineStyle () {
                let that = this;
                const {jude, object2style} = that.$util;
                const scale = jude.isNumberOfNaN(that.scale) ? that.scale : 0.8;
                this.lineStyle_ = object2style({width: scale * 100 + '%'});
            },
            init: debounce(function () {
                const that = this;
                that.isClick = false;
                that.setLineStyle();
                const fIndex = this.setActive();
                // if (fIndex !== that.value && that.tabs) that.$emit('input', fIndex);
            }, 300),
            handleTabSelect (e) {
                const that = this;
                that.isClick = true;
                const active = that.$util.getNumber(e.currentTarget.dataset.id, 0);
                if (active !== that.active) {
                    const val = that.tabs[active];
                    that.__emit(that.tabs[active], 'change')
                }
                that.active = active;
                const {id, offsetLeft} = e.currentTarget;
                that.setLineAnimation(id, offsetLeft, true);
                that.__emit(e)
            },
            setLineAnimation (id, offsetLeft, bol = false) {
                let that = this;
                const {windowWidth} = that.systemInfo;
                const {object2style} = that.$util;
                const SelectorQuery = uni.createSelectorQuery().in(this);
                const NodesRef = SelectorQuery
                    .select(`#${id}`).boundingClientRect()
                    .select(`#${id} .cu-item__box`).boundingClientRect();
                that.$nextTick(function () {
                    NodesRef.exec(function ([a, d, c]) {
                        if (!a || !d) return;
                        const bl = d.left - a.left;
                        if (!that.$util.jude.isNumberOfNaN(offsetLeft)) {
                            offsetLeft = d.left
                        }
                        let scale = that.$util.getNumber(that.scale, 1);
                        const style = {
                            left: offsetLeft + bl + (d.width / 2) + 'px',
                            width: d.width * scale + 'px'
                        };
                        that.lineStyle = object2style(style);
                        // if (!bol) that.active_id = id;
                        if (a.left < 0 || a.right > windowWidth) that.active_id = id;
                    });
                })
            },
            setLineAnimation2 (id) {
                let that = this;
                const {windowWidth} = that.systemInfo;
                const {object2style} = that.$util;
                const SelectorQuery = uni.createSelectorQuery().in(this);
                const NodesRef = SelectorQuery
                    .select(`#${id}`).boundingClientRect()
                    .select(`#${id} .cu-item__box__line`).boundingClientRect();
                that.$nextTick(function () {
                    NodesRef.exec(function ([a, d, c]) {
                        if (d) {
                            const style = {
                                left: d.left + 'px',
                                width: d.width + 'px'
                            };
                            that.lineStyle = object2style(style);
                        }
                        if (a && (a.left < 0 || a.right > windowWidth))
                            that.active_id = id;
                    })
                })
            },
            __emit (e, type) {
                this.$emit(type || e.type, e)
            }
        }
    }
</script>

<style scoped lang="scss">
    .tl-tabs-components {
        min-height: 40*2upx;


        .cu-item {
            color: #A2A8A8;
            font-size: 15*2upx;
            font-weight: bold;
            height: 40*2upx;
            line-height: 40*2upx;

            &.cu-item__active {
                > .cu-item__box {
                    position: relative;
                    color: #313131;
                    width: 100%;
                    height: 100%;

                    .cu-item__box__line {
                        position: absolute;
                        left: 50%;
                        bottom: 0;
                        transform: translateX(-50%);
                        border-bottom: 2px solid $tl-color-primary;
                        width: 100%;
                    }

                    &.no-border:after {
                        border-width: 0;
                    }
                }
            }
        }

        .flex {
            position: relative;

            .tl-tabs__line {
                width: 20*2px;
                position: absolute;
                bottom: 0;
                left: 0;
                border-bottom: 2px solid $tl-color-primary;
                transform: translateX(-50%);
                transition: left .3s;
            }
        }
    }
</style>
